package nettyexample;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * @author zoush
 * @time 2024/12/17 17:29
 */
public class FirstServerHandler  extends ChannelInboundHandlerAdapter {

   public void channelActive(io.netty.channel.ChannelHandlerContext ctx) throws Exception {
       System.out.println("客户端发送数据");

       //获取数据
       ByteBuf byteBuf = getByteBuf(ctx);
       //写数据
       ctx.channel().writeAndFlush(byteBuf);
   }

   private ByteBuf getByteBuf(io.netty.channel.ChannelHandlerContext ctx) {
        //获取二进制抽象ByteBuf
       ByteBuf buffer = ctx.alloc().buffer();
       //准备数据 制定字符集为UTF_8
       String text = "你好，欢迎关注我";
       byte[] bytes = text.getBytes(Charset.forName("utf-8"));
       //写入数据到buffer
       buffer.writeBytes(bytes);
       return buffer;

   }

    @Override
    public void channelRead(io.netty.channel.ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server channelRead..");
        ctx.channel().writeAndFlush("server writeAndFlush");
    }
}
